import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _indexOf from "lodash/indexOf";
import _uniqBy from "lodash/uniqBy";
import _isEmpty from "lodash/isEmpty";
import _map from "lodash/map";
var _excluded = ["_data"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _class;

import React from 'react';
import { Form, Input, InputNumber, Popconfirm, Switch, Icon } from 'antd';
import { Bind } from 'lodash-decorators';
import EditTable from 'components/EditTable';
import { operatorRender, TagRender } from 'utils/renderer';
import intl from 'utils/intl';
import { tableScrollWidth, getCurrentLanguage } from 'utils/utils';
import MultiInfoModal from "./MultiInfoModal";
import "./index.less";
var FormItem = Form.Item;
var List = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(List, _React$Component);

  var _super = _createSuper(List);

  function List() {
    var _this;

    _classCallCheck(this, List);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      editableKey: null,
      prevDataSource: [],
      dataSource: [],
      visible: false,
      // modal visible
      modalData: [],
      // modal的数据源
      dataIndex: null,
      // 当前列名
      currentRecord: {} // 当前编辑的这条记录

    };
    return _this;
  }

  _createClass(List, [{
    key: "edit",
    value:
    /**
     * 编辑的时候，将当前记录更新为record,但是此时的record是没有$form的
     * @param {*} record
     * @param {*} editableKey
     */
    function edit(record, editableKey) {
      var _this$state$dataSourc = this.state.dataSource,
          dataSource = _this$state$dataSourc === void 0 ? [] : _this$state$dataSourc;
      this.setState({
        editableKey: editableKey,
        currentRecord: record,
        dataSource: dataSource.map(function (rd) {
          return (// eslint-disable-next-line no-nested-ternary
            rd._id === editableKey ? _objectSpread(_objectSpread({}, rd), {}, {
              _status: 'update'
            }) : rd._status ? _objectSpread(_objectSpread({}, rd), {}, {
              _status: ''
            }) : rd
          );
        })
      });
    }
  }, {
    key: "cancel",
    value: function cancel() {
      var _this$state$dataSourc2 = this.state.dataSource,
          dataSource = _this$state$dataSourc2 === void 0 ? [] : _this$state$dataSourc2;
      this.setState({
        editableKey: null,
        dataSource: dataSource.map(function (rd) {
          return rd._status ? _objectSpread(_objectSpread({}, rd), {}, {
            _status: ''
          }) : rd;
        }) // currentRecord: {},
        // dataIndex: null,

      });
    }
  }, {
    key: "handleSave",
    value: function handleSave(form, _id) {
      var _this$props$save = this.props.save,
          save = _this$props$save === void 0 ? function (e) {
        return e;
      } : _this$props$save;
      var currentRecord = this.state.currentRecord;
      save(form, _id, currentRecord, this.cancel);
    }
  }, {
    key: "handleRemove",
    value: function handleRemove(_id) {
      var onRemove = this.props.onRemove;
      onRemove(_id, this.cancel);
    }
  }, {
    key: "editRender",
    value: function editRender(text, record) {
      var _this2 = this;

      var editableKey = this.state.editableKey;
      var operators = [];

      if (editableKey === record._id && record._status) {
        var form = record.$form;
        operators.push({
          key: 'save',
          ele: /*#__PURE__*/React.createElement("a", {
            onClick: function onClick() {
              return _this2.handleSave(form, record._id);
            }
          }, intl.get('cpaas.common.button.save').d('保存')),
          len: 2,
          title: intl.get('cpaas.common.button.save').d('保存')
        });
        operators.push({
          key: 'cancel',
          ele: /*#__PURE__*/React.createElement(Popconfirm, {
            title: intl.get("cimp.comment.view.message.title.sureToCancel").d('确定取消编辑？'),
            onConfirm: function onConfirm() {
              return _this2.cancel();
            }
          }, /*#__PURE__*/React.createElement("a", null, intl.get('cpaas.common.button.cancel').d('取消'))),
          len: 2,
          title: intl.get('cpaas.common.button.cancel').d('取消')
        });
      } else if (!record.imported) {
        operators.push({
          key: 'edit',
          ele: /*#__PURE__*/React.createElement("a", {
            onClick: function onClick() {
              return _this2.edit(record, record._id);
            }
          }, intl.get('cpaas.common.button.edit').d('编辑')),
          len: 2,
          title: intl.get('cpaas.common.button.edit').d('编辑')
        });
      }

      return operatorRender(operators, record);
    }
  }, {
    key: "getDynamicColumns",
    value: function getDynamicColumns() {
      var _this3 = this;

      var _this$props$dynamicCo = this.props.dynamicColumns,
          dynamicColumns = _this$props$dynamicCo === void 0 ? [] : _this$props$dynamicCo;
      var _this$state = this.state,
          editableKey = _this$state.editableKey,
          _this$state$dataSourc3 = _this$state.dataSource,
          dataSource = _this$state$dataSourc3 === void 0 ? [] : _this$state$dataSourc3;
      return dynamicColumns.map(function (n) {
        return {
          title: n.title,
          dataIndex: n.dataIndex,
          width: dataSource.some(function (o) {
            return o._id === editableKey;
          }) || !n.width ? 180 : n.width,
          render: function render(text, record) {
            var form = record.$form; // when editableKey is equal record._id, it can edit, but, check _status to decide it can edit

            return editableKey === record._id && record._status ? /*#__PURE__*/React.createElement(FormItem, {
              style: {
                margin: 0
              }
            }, form.getFieldDecorator(n.dataIndex, {
              rules: [{
                required: n.required,
                message: intl.get('cpaas.common.validation.notNull', {
                  name: n.title
                })
              }],
              initialValue: _this3.setInitValue(record[n.dataIndex])
            })(_this3.getInput(n.columnType, record, n.dataIndex, n.tls))) : text;
          }
        };
      });
    }
  }, {
    key: "setInitValue",
    value: function setInitValue(value) {
      if (value === 'true' || value === 'false') {
        return value === 'true';
      } else {
        return value;
      }
    }
  }, {
    key: "getInput",
    value: function getInput(type, record, dataIndex, _tls) {
      var _this4 = this;

      switch (type) {
        case 'String':
          return /*#__PURE__*/React.createElement(Input, null);

        case 'Decimal':
          return /*#__PURE__*/React.createElement(InputNumber, null);

        case 'Long':
          return /*#__PURE__*/React.createElement(InputNumber, null);

        case 'Boolean':
          return /*#__PURE__*/React.createElement(Switch, {
            checkedValue: true,
            unCheckedValue: false
          });
        // 类多语言框

        case 'Multi':
          return /*#__PURE__*/React.createElement(Input, {
            className: "multi-info-input",
            readOnly: true,
            style: {
              cursor: 'pointer'
            },
            suffix: /*#__PURE__*/React.createElement(Icon, {
              type: "global",
              onClick: function onClick() {
                return _this4.handleOpenModal(record, dataIndex, _tls);
              }
            }),
            onClick: function onClick() {
              return _this4.handleOpenModal(record, dataIndex, _tls);
            }
          });
        // case 'Date':
        //   return <Switch />;

        default:
          return /*#__PURE__*/React.createElement(Input, null);
      }
    }
  }, {
    key: "handleOpenModal",
    value: function handleOpenModal(record, dataIndex) {
      var tls = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
      var _this$props$languageT = this.props.languageType,
          languageType = _this$props$languageT === void 0 ? [] : _this$props$languageT;
      var currentRecord = this.state.currentRecord; // 当前如果是第一次打开，那么_tls就取当前record的数据，否则取state中的currentRecord

      var _ref = currentRecord.$form ? currentRecord : record,
          _ref$_tls = _ref._tls,
          _tls = _ref$_tls === void 0 ? {} : _ref$_tls;

      var data = {};
      var dataSource = [];
      var formItemData = [];
      /**
       * 字段FormItem从info接口中取
       */

      var formI = tls[dataIndex];
      Object.keys(formI).forEach(function (r, ri) {
        Object.values(formI).forEach(function (res, resi) {
          if (ri === resi) {
            formItemData.push({
              lang: r,
              value: ''
            });
          }
        });
      }); // if (record !== currentRecord || dataIndex !== stateDataIndex) {

      /**
       * 获取到当前字段JSON
       */

      Object.keys(_tls).forEach(function (item, index) {
        if (item === dataIndex) {
          Object.values(_tls).forEach(function (i, d) {
            if (index === d) {
              data = i;
            }
          });
        }
      });
      /**
       * 将当前字段JSON处理为数组，此时的字段含有字段和字段值
       */

      Object.keys(data).forEach(function (r, ri) {
        Object.values(data).forEach(function (res, resi) {
          if (ri === resi) {
            dataSource.push({
              lang: r,
              value: res
            });
          }
        });
      });
      /**
       * 将formItem和dataSource合并到一起，防止出现没有FormItem的情况
       */

      var newData = _uniqBy([].concat(dataSource, formItemData), 'lang');
      /**
       * 将数据与语言值集对比，添加meaning
       */


      var newModalData = [];
      var types = languageType.map(function (l) {
        return l.code;
      });
      languageType.forEach(function (k) {
        newData.forEach(function (j) {
          if (k.code === j.lang) {
            newModalData.push(_objectSpread(_objectSpread({}, j), {}, {
              meaning: k.meaning
            }));
          } else if (!types.includes(j.lang)) {
            newModalData.push(j);
          }
        });
      });

      var filterModalData = _uniqBy(newModalData, 'lang');

      var flag = _isEmpty(currentRecord.$form);

      this.setState({
        visible: true,
        modalData: filterModalData,
        dataIndex: dataIndex,
        currentRecord: flag ? record : currentRecord
      }); // } else {
      //   this.setState({
      //     visible: true,
      //     dataIndex,
      //   });
      // }
    }
  }, {
    key: "handleCancel",
    value: function handleCancel() {
      this.setState({
        visible: false,
        modalData: []
      });
    }
    /**
     * modal确定的时候，需要把最新的当前数据更新到currentRecord中，以防下一次打开获取到的是旧的数据
     * @param {*} data
     */

  }, {
    key: "handleModalOk",
    value: function handleModalOk() {
      var _objectSpread3;

      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      var _this$state2 = this.state,
          _this$state2$modalDat = _this$state2.modalData,
          modalData = _this$state2$modalDat === void 0 ? [] : _this$state2$modalDat,
          _this$state2$currentR = _this$state2.currentRecord,
          currentRecord = _this$state2$currentR === void 0 ? {} : _this$state2$currentR,
          dataIndex = _this$state2.dataIndex; // 获取当前语言

      var currentLanguage = getCurrentLanguage();

      var _currentRecord$_tls = currentRecord._tls,
          _tls = _currentRecord$_tls === void 0 ? {} : _currentRecord$_tls;

      var keys = Object.keys(data);
      var values = Object.values(data);

      var index = _indexOf(keys, currentLanguage);

      var newData = []; // 获取到modal里的新数据

      keys.forEach(function (key, ki) {
        modalData.forEach(function (m) {
          if (m.lang === key) {
            newData.push(_objectSpread(_objectSpread({}, m), {}, {
              value: values[ki]
            }));
          }
        });
      }); // 给外层的Input赋值，并且需要根据当前语言，渲染不同的值

      currentRecord.$form.setFieldsValue(_defineProperty({}, dataIndex, values[index])); // 转换为后端需要的格式

      var newTls = _objectSpread(_objectSpread({}, _tls), {}, _defineProperty({}, dataIndex, _objectSpread(_objectSpread({}, _tls[dataIndex]), data)));

      var newCurrentRecord = _objectSpread(_objectSpread({}, currentRecord), {}, (_objectSpread3 = {}, _defineProperty(_objectSpread3, dataIndex, values[0]), _defineProperty(_objectSpread3, "_tls", newTls), _objectSpread3));

      this.setState({
        modalData: newData,
        visible: false,
        currentRecord: newCurrentRecord
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;

      var _this$props = this.props,
          _this$props$processin = _this$props.processing,
          processing = _this$props$processin === void 0 ? {} : _this$props$processin,
          pagination = _this$props.pagination,
          onChange = _this$props.onChange;
      var _this$state3 = this.state,
          _this$state3$dataSour = _this$state3.dataSource,
          dataSource = _this$state3$dataSour === void 0 ? [] : _this$state3$dataSour,
          _this$state3$visible = _this$state3.visible,
          visible = _this$state3$visible === void 0 ? false : _this$state3$visible,
          _this$state3$modalDat = _this$state3.modalData,
          modalData = _this$state3$modalDat === void 0 ? [] : _this$state3$modalDat,
          _this$state3$dataInde = _this$state3.dataIndex,
          dataIndex = _this$state3$dataInde === void 0 ? null : _this$state3$dataInde;
      var dynamicColumns = this.getDynamicColumns();
      var beforeColumns = [{
        title: intl.get('cimp.comment.model.comment.dataStatus').d('数据状态'),
        dataIndex: '_dataStatus',
        width: 120,
        fixed: 'left',
        render: function render(_dataStatus) {
          var _this5$props$importSt = _this5.props.importStatus,
              importStatus = _this5$props$importSt === void 0 ? [] : _this5$props$importSt;
          var statusList = [{
            status: 'NEW',
            color: 'blue'
            /* , text: 'Excel导入' */

          }, {
            status: 'VALID_SUCCESS',
            color: 'green'
            /* , text: '验证成功' */

          }, {
            status: 'VALID_FAILED',
            color: 'red'
            /* , text: '验证失败' */

          }, {
            status: 'IMPORT_SUCCESS',
            color: 'green'
            /* , text: '导入成功' */

          }, {
            status: 'IMPORT_FAILED',
            color: 'red'
            /* , text: '导入失败' */

          }, {
            status: 'ERROR',
            color: 'red'
            /* , text: '数据异常' */

          }];
          return /*#__PURE__*/React.createElement("div", null, TagRender(_dataStatus, importStatus.map(function (item) {
            var tagItem = statusList.find(function (t) {
              return t.status === item.value;
            }) || {};
            return {
              status: item.value,
              text: item.meaning,
              color: tagItem.color
            };
          })));
        }
      }, {
        title: intl.get('cimp.comment.model.comment.message').d('信息'),
        dataIndex: '_info'
      }];
      var afterColumns = [{
        title: intl.get('cpaas.common.button.action').d('操作'),
        width: 110,
        key: '_operator',
        render: this.editRender,
        fixed: 'right'
      }];
      var tableColumns = [].concat(beforeColumns, _toConsumableArray(dynamicColumns), afterColumns);
      var tableProps = {
        dataSource: dataSource,
        pagination: pagination,
        onChange: onChange,
        rowKey: '_id',
        bordered: true,
        loading: processing.loading || processing.queryColumns,
        columns: tableColumns,
        scroll: {
          x: tableScrollWidth(tableColumns)
        }
      };
      var modalProps = {
        visible: visible,
        modalData: modalData,
        dataIndex: dataIndex,
        onCancel: this.handleCancel,
        onOk: this.handleModalOk
      };
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(EditTable, tableProps), /*#__PURE__*/React.createElement(MultiInfoModal, modalProps));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var dataSource = nextProps.dataSource;

      if (dataSource !== prevState.prevDataSource) {
        return {
          dataSource: _map(dataSource, function (record) {
            var _data = record._data,
                rest = _objectWithoutProperties(record, _excluded);

            var rData;

            try {
              rData = JSON.parse(_data);
            } catch (e) {
              rData = {};
            }

            return _objectSpread(_objectSpread({}, rData), rest);
          }),
          prevDataSource: dataSource
        };
      }

      return null;
    }
  }]);

  return List;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "edit", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "edit"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "cancel", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "cancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleSave", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleSave"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleRemove", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "handleRemove"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "editRender", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "editRender"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "getDynamicColumns", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "getDynamicColumns"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "getInput", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "getInput"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleOpenModal", [_dec8], Object.getOwnPropertyDescriptor(_class.prototype, "handleOpenModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleCancel", [_dec9], Object.getOwnPropertyDescriptor(_class.prototype, "handleCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleModalOk", [_dec10], Object.getOwnPropertyDescriptor(_class.prototype, "handleModalOk"), _class.prototype)), _class));
export { List as default };